package io.renren.modules.nuaa.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.nuaa.dto.TCategoryDTO;
import io.renren.modules.nuaa.dto.TQuestionDTO;
import io.renren.modules.nuaa.dto.TQuestionItemDTO;
import io.renren.modules.nuaa.dto.TQuestionOptionsDTO;
import io.renren.modules.nuaa.entity.TQuestionItemEntity;
import io.renren.modules.nuaa.excel.TQuestionExcel;
import io.renren.modules.nuaa.service.TCategoryService;
import io.renren.modules.nuaa.service.TQuestionItemService;
import io.renren.modules.nuaa.service.TQuestionOptionsService;
import io.renren.modules.nuaa.service.TQuestionService;
import io.renren.modules.security.user.SecurityUser;
import io.renren.modules.sys.dto.SysUserDTO;
import io.renren.modules.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
* 问卷
*
* @author whc 15953295779@126.com
* @since 3.0 2023-11-03
*/
@RestController
@RequestMapping("nuaa/tquestion")
@Api(tags="问卷")
public class TQuestionController {
    @Autowired
    private TQuestionService tQuestionService;

    @Autowired
    private TQuestionItemService tQuestionItemService;

    @Autowired
    private TQuestionOptionsService tQuestionOptionsService;

    @Autowired
    private TCategoryService tCategoryService;
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private ResourceLoader resourceLoader;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    @RequiresPermissions("nuaa:tquestion:page")
    public Result<PageData<TQuestionDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params){
        PageData<TQuestionDTO> page = tQuestionService.page(params);

        List<TQuestionDTO> tQuestionDTOList = page.getList();

        tQuestionDTOList.forEach(dto ->{
            if(StringUtils.isNotEmpty(dto.getCreator())) {
                SysUserDTO creatorUser = sysUserService.get(Long.parseLong(dto.getCreator()));
                dto.setCreator(creatorUser.getRealName());
            }
            if(StringUtils.isNotEmpty(dto.getUpdater())) {
                SysUserDTO updaterUser = sysUserService.get(Long.parseLong(dto.getUpdater()));
                dto.setUpdater(updaterUser.getRealName());
            }

            TCategoryDTO tCategoryDTO = tCategoryService.get(dto.getCategoryId().longValue());
            dto.setCategoryName(tCategoryDTO.getCategoryName());
        });

        return new Result<PageData<TQuestionDTO>>().ok(page);
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    @RequiresPermissions("nuaa:tquestion:info")
    public Result<TQuestionDTO> get(@PathVariable("id") Long id){
        TQuestionDTO data = tQuestionService.get(id);

        return new Result<TQuestionDTO>().ok(data);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    @RequiresPermissions("nuaa:tquestion:save")
    public Result save(@RequestBody TQuestionDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);

        dto.setCreateDate(new Date());
        dto.setCreator(SecurityUser.getUserId().toString());
        dto.setUpdateDate(new Date());
        dto.setUpdater(SecurityUser.getUserId().toString());

        tQuestionService.save(dto);

        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    @RequiresPermissions("nuaa:tquestion:update")
    public Result update(@RequestBody TQuestionDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        dto.setUpdateDate(new Date());
        dto.setUpdater(SecurityUser.getUserId().toString());

        tQuestionService.update(dto);

        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    @RequiresPermissions("nuaa:tquestion:delete")
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        tQuestionService.delete(ids);

        return new Result();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    @RequiresPermissions("nuaa:tquestion:export")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<TQuestionDTO> list = tQuestionService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, "问卷", list, TQuestionExcel.class);
    }
    //保存问卷及题目
    @PostMapping("saveQuestion")
    public  Result  saveItem( @RequestBody TQuestionDTO question ){
        tQuestionService.addOrUpdate(question);

        return new Result();
    }
    /**
     * 获取题目
     */
    @GetMapping("queryQuestion")
    public  Result  queryQuestion(Integer  categoryId ,Integer hourId){
        TQuestionDTO fiiQuestionDTO = tQuestionService.getQuestion(categoryId);

        return new Result<TQuestionDTO>().ok(fiiQuestionDTO);
    }

    /**
     * 导入题目表格
     * @param file
     * @param id
     * @return
     * @throws Exception
     */
    @PostMapping("import/{id}")
    @ApiOperation("导入")
    @ApiImplicitParam(name = "file", value = "文件", paramType = "query", dataType="file")
    public Result importExcel(@RequestParam("file") MultipartFile file,@PathVariable Long id) throws Exception {
        //根据问卷id，查询查询出所有问题项并删除
        List<TQuestionItemEntity> tQuestionItemEntityList = tQuestionItemService.selectByQuestionId(id);
        if(CollectionUtils.isNotEmpty(tQuestionItemEntityList)){
            List<Long> collect = tQuestionItemEntityList.stream().map(TQuestionItemEntity::getId).collect(Collectors.toList());

            tQuestionItemService.delete(collect.toArray(new Long[collect.size()]));
        }

        List<Object> read = EasyExcel.read(file.getInputStream(), new Sheet(1));
        TQuestionItemDTO tQuestionItemDTO = null;
        for(Object object : read){

            List<String> list = (List<String>) object;
            if(list.size() == 4 && list.get(0) != null){
                tQuestionItemDTO = new TQuestionItemDTO();
                tQuestionItemDTO.setTitle(list.get(0));

                if("单选".equals(list.get(1))){
                    tQuestionItemDTO.setType(1);
                }else if("多选".equals(list.get(1))){
                    tQuestionItemDTO.setType(2);
                }
                tQuestionItemDTO.setScore(Integer.parseInt(list.get(2)));
                tQuestionItemDTO.setStandard(list.get(3));
                tQuestionItemDTO.setCreateDate(new Date());
                tQuestionItemDTO.setUpdateDate(new Date());
                tQuestionItemDTO.setCreator(SecurityUser.getUserId().toString());
                tQuestionItemDTO.setUpdater(SecurityUser.getUserId().toString());
                tQuestionItemDTO.setQuestionId(id.intValue());

                tQuestionItemService.save(tQuestionItemDTO);

            }else if(list.size() == 3 && list.get(0) == null){
                TQuestionOptionsDTO tQuestionOptionsDTO = new TQuestionOptionsDTO();

                tQuestionOptionsDTO.setItemId(tQuestionItemDTO.getId().intValue());
                tQuestionOptionsDTO.setValue(list.get(1));
                tQuestionOptionsDTO.setTitle(list.get(2));
                tQuestionOptionsDTO.setCreateAt(new Date());
                tQuestionOptionsDTO.setUpdateAt(new Date());
                tQuestionOptionsDTO.setCreator(SecurityUser.getUserId().toString());
                tQuestionOptionsDTO.setUpdator(SecurityUser.getUserId().toString());

                tQuestionOptionsService.save(tQuestionOptionsDTO);

            }

        }
        return new Result();
    }
    /**
     * 下载excel模板
     */
    @GetMapping("downloadExcel")
    public void downloadExcel(HttpServletResponse response) throws IOException {




        response.setContentType("application/force-download");
        response.setHeader("Content-Disposition","attachment;filename=excel.xlsx");
        Resource fileResource = new ClassPathResource("/statics/excel/excel.xlsx");

        InputStream input = fileResource.getInputStream();

        byte data[] = new byte[1024];
        int len;
        while((len=input.read(data)) != -1){
            response.getOutputStream().write(data,0,len);
        }

    }

}